package com.tanami.rynmar;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.os.AsyncTask;
import android.util.Log;

public class PriceListParsingTask extends AsyncTask<ByteArrayOutputStream, Integer, PriceListXmlContent> {
    
	private WeakReference<RynmarActivity>	mParentActivity = null;
	private ByteArrayOutputStream		mInputStream = null;

	public PriceListParsingTask(RynmarActivity parentActivity) {
        mParentActivity = new WeakReference<RynmarActivity>(parentActivity);
    }
	
	/*
	 * doInBackground
	 * 
	 * */
	protected PriceListXmlContent doInBackground(ByteArrayOutputStream... is) {
		
		mInputStream = is[0];
				
    	PriceListXmlContent data = _parseXml();
    	
    	return data;
    }

	/*
	 * onPostExecute
	 * */
    protected void onPostExecute(PriceListXmlContent data) {
    	// now we do something that requires the context
        if (mParentActivity.get() != null) {
            // the WeakReference is still valid and hasn't been reclaimed
            // by the GC
            final RynmarActivity parentActivity = mParentActivity.get();
            
            byte[] byteArray = mInputStream.toByteArray();
            
            parentActivity.OnParseComplete(byteArray, data);
        }
    }
    
    /*
     * Sax parser
     * */
    private PriceListXmlContent _parseXml() { 
    	PriceListXmlContent data = null; 
    	 
    	  // sax stuff 
    	  try { 
    	    SAXParserFactory spf = SAXParserFactory.newInstance(); 
    	    SAXParser sp = spf.newSAXParser(); 
    	 
    	    XMLReader xr = sp.getXMLReader(); 
    	 
    	    PriceListContentHandler dataHandler = new PriceListContentHandler(); 
    	    xr.setContentHandler(dataHandler); 
    	 
    	    ByteArrayInputStream bis = new ByteArrayInputStream(mInputStream.toByteArray());
    	    
    	    xr.parse(new InputSource(bis)); 
    	 
    	    data = dataHandler.getData(); 
    	 
    	  } catch(ParserConfigurationException pce) { 
    	    Log.e("SAX XML", "sax parse error", pce); 
    	  } catch(SAXException se) { 
    	    Log.e("SAX XML", "sax error", se); 
    	  } catch(IOException ioe) { 
    	    Log.e("SAX XML", "sax parse io error", ioe); 
    	  } 
    	 
    	  return data; 
    	} 
}